package com.cszjzx.member.service;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.ietf.jgss.Oid;

import com.cszjzx.member.dao.*;
import com.cszjzx.member.po.*;

public class MajorServiceImpl implements MajorService {
	
	private MajorDAO majorDAO ;
	private MemberDAO memberDAO;
	
	public MajorServiceImpl() {
		try{
			majorDAO = new MajorDAOImpl();
			memberDAO = new MemberDAOImpl();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	

	@Override
	public List<Major> getMajorsByDepartmentId(int departmentId) {
		
		List<Major> majors = null;
		try {
			majors = majorDAO.findByDepartmentId(departmentId);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return majors;
	}

	@Override
	public boolean addMajor(String name, int departmentId) {
		
		Major major = new Major(name, departmentId);
		try {
			majorDAO.add(major);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean deleteMajors(int id) {
		
		try {
				majorDAO.dalete(id);
		} catch (SQLException e){
			e.printStackTrace();
			return false;
		}
		return true;
	}


	@Override
	public List<Major> getMajorsByDeapartmentAndProcess(int departmentId, String departmentName, String process) {
		
		List<Major> majors = null;
		try {
			majors = majorDAO.findByDepartmentId(departmentId);
			for(int i=0;i<majors.size();i++){
				majors.get(i).setNums(0);
			}
			
			List<Member> members = memberDAO.findByDepartmentNameAndProcess(departmentName,process);
			for(int i=0;i<members.size();i++){
				String m = members.get(i).getValue("major");
				for(int j=0;j<majors.size();j++){
					if(majors.get(j).getName().equals(m)){
						majors.get(j).setNums(majors.get(j).getNums()+1);
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return majors;
	}


	@Override
	public List<Major> getMajorsByDepartmentName(String departmentName) {
		List<Major> majors = null;
		try {
			majors = majorDAO.findByDepartmentName(departmentName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return majors;
	}
}
